<template>
  <div class="dashboard-editor-container">
    <!-- 数据看板 -->
    <panel-group />
    <!-- 柱状图 -->

    <el-row style="background: #fff; padding: 16px 16px 0; margin-bottom: 32px">
      <div class="charts">
        <div class="header">
          <p>
            <span>客户数据分析</span>
          </p>
          <div class="top_right">
            <div class="picker_select">
              <el-select
                v-model="yyName"
                clearable
                filterable
                placeholder="请选择"
                size="small"
              >
                  <!-- multiple 
                collapse-tags -->
                <el-option
                  v-for="items in yylist.list"
                  :key="items.id"
                  :label="items.applicationName"
                  :value="items.id"
                ></el-option>
              </el-select>
            </div>

            <div class="picker_select">
              <!-- v-if='canvasType==2' -->
              <el-select
                v-model="result"
                clearable
                filterable
                placeholder="请选择"
                size="small"
              >
                <el-option label="新增客户数" value="1"></el-option>
                <el-option label="总客户数" value="3"></el-option>
              </el-select>
            </div>

            <el-date-picker
              v-model="time"
              type="daterange"
              :picker-options="pickerOptions2"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
              format="yyyy- MM- dd"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
            <el-button type="primary" size="mini" @click="canvasSearch"
              >刷新</el-button
            >
          </div>
        </div>
        <!-- t图标 -->
        <div class="graphical">
          <!-- 部门整体销售 -->
          <div class="group">
            <div class="groupTitle">
              <div class="checked">
                <el-radio-group v-model="canvasType" @change="changeCanvasType">
                  <el-radio :label="1">折线图</el-radio>
                  <el-radio :label="2">柱状图</el-radio>
                </el-radio-group>

                <el-radio-group
                  v-if="canvasType != 2"
                  v-model="lineType"
                  @change="dayMothon"
                >
                  <el-radio :label="1">按天展示</el-radio>
                  <el-radio :label="2">按月展示</el-radio>
                </el-radio-group>
              </div>
              <!-- <p @click="teamEvent()">
                <span>查看详情 ></span>
              </p> -->
            </div>
            <div class="echart1">
              <div
                v-show="canvasType == '1'"
                id="bumen"
                style="width: 100%; height: 300px"
              ></div>

              <div
                v-show="canvasType == '2'"
                id="bumenZZ"
                style="width: 100%; height: 300px"
              ></div>
              <!-- <bar-chart v-if="canvasType == '2'" width="100%" /> -->
            </div>
          </div>
        </div>
      </div>
      <!-- </div> -->
    </el-row>

    <div class="list">
      <div class="addcur">
        <span>新增客户数</span>
        <div class="listright">
          <div class="picker_select">
            <el-select
              v-model="listSearch"
              clearable
              filterable
              placeholder="请选择"
              size="small"
            >
              <el-option
                v-for="items in yylist.list"
                :key="items.id"
                :label="items.applicationName"
                :value="items.id"
              ></el-option>
            </el-select>
          </div>
          <el-button type="primary" size="mini" @click="addlistRefresh"
            >刷新</el-button
          >
        </div>
      </div>
      <el-table :data="customerApplist.list" width="100%">
        <el-table-column
          label="序号"
          type="index"
          width="80px;"
        ></el-table-column>
        <el-table-column
          label="应用名称"
          prop="applicationName"
        ></el-table-column>
        <el-table-column label="新增客户数" prop="addMember"></el-table-column>
        <el-table-column label="总客户数" prop="member"></el-table-column>
      </el-table>
      <p style="height: 30px"></p>
      <!-- 分页start -->
      <div class="page">
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage1"
            :page-sizes="[10, 20, 50, 100, 200]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="customerApplist.totalNum"
            prev-text="上一页"
            next-text="下一页"
          >
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 弹框 -->
    <!-- <el-dialog :visible.sync="Visible" :append-to-body="true" title="分配资源">
    </el-dialog> -->
    <!-- 弹框 -->
  </div>
</template>
<script>
import PanelGroup from "./components/PanelGroup";
import BarChart from "./components/BarChart";
import LineChart from "./components/LineChart";
import resize from "./components/mixins/resize";
import api from "./../api/common.js";

export default {
  mixins: [resize],
  components: {
    PanelGroup,
    BarChart,
    LineChart,
  },
  data() {
    return {
      pickerOptions2: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      time: this.getTimeAlready(7),
      canvasType: 1, //图类型
      lineType: 1, //按 日，月
      lineChartData: {},
      tablelist: [],
      pageSize: 10,
      currentPage1: 1,
      Visible: false,
      yylist: [],
      yyName: [],
      customerApplist: "",
      listSearch: "", //新增客户数
      result: "3", //图形数据的类型
    };
  },
  created() {
    api.selectType().then((res) => {
      if (res.code == 0) {
        this.yylist = res.data;
      } else {
        this.$message.error(res.message);
      }
    });
    this.newCustomer();
  },
  mounted() {
    this.$nextTick(() => {
      this.canvasDate();
    });
    setTimeout(() => {
      if (this.teamChart) {
        this.teamChart.resize();
      }

      if (this.myChart1) {
        this.myChart1.resize();
      }
    }, 2000);
  },
  methods: {
    // 获取将近前一个月的时间
    getTimeAlready(param) {
      const end = new Date();
      const start = new Date();
      const time = start.setTime(start.getTime() - 3600 * 1000 * 24 * param);
      const endTime = /\d{4}-\d{1,2}-\d{1,2}/g.exec(this.$moment(end))[0];
      const startTime = /\d{4}-\d{1,2}-\d{1,2}/g.exec(this.$moment(time))[0];
      return [startTime, endTime];
    },
    // 改变图形
    changeCanvasType(e) {
      this.canvasType = e;
      this.canvasDate();
      document.getElementById("bumen").removeAttribute("_echarts_instance_"); // 移除容器上的 _echarts_instance_ 属性
      document.getElementById("bumenZZ").removeAttribute("_echarts_instance_");
    },
    // 选择日，月
    dayMothon(e) {
      this.lineType = e;
      if (e == 2) {
        this.time = this.getTimeAlready(30);
      }else{
        this.time = this.getTimeAlready(7);
      }
      this.canvasDate();
      document.getElementById("bumen").removeAttribute("_echarts_instance_"); // 移除容器上的 _echarts_instance_ 属性
      document.getElementById("bumenZZ").removeAttribute("_echarts_instance_");
    },
    canvasSearch() {
      this.canvasDate();
      document.getElementById("bumen").removeAttribute("_echarts_instance_"); // 移除容器上的 _echarts_instance_ 属性
      document.getElementById("bumenZZ").removeAttribute("_echarts_instance_");
    },
    canvasDate() {
      let beginTime = "",
        endTime = "";
      if (this.time) {
        beginTime = this.time[0] + " 00:00:00";
        endTime = this.time[1] + " 23:59:59";
      }
      // let applicationId = [];
      // applicationId.push(this.yyName);
      this.axios
        .post("/member/v1/member/statistics", {
          applicationId: this.yyName,
          queryType: this.result == "" ? 3 : this.result, //查询类型
          endTime: endTime,
          lineType: this.lineType, //1天 2 月
          startTime: beginTime,
          type: this.canvasType, // 1折线 2树状
        })
        .then((res) => {
          // console.log(res);
          if (res.code == 0) {
            if (res.code == 0 && JSON.stringify(res.data) != "{}") {
              var xdata = [];
              var ydata = [];
              var datatotal = [];
              this.titleSvg = [];
              if (this.canvasType == "1") {
                for (let key in res.data) {
                  this.titleSvg.push(key);
                  datatotal.push(res.data[key]);
                  xdata.push({
                    type: "line",
                    symbol: "none",
                    smooth: true,
                    name: key,
                    animationDuration: 2800,
                    animationEasing: "quadraticOut",
                    data: [],
                  });
                }
                // 获取x轴的数据
                datatotal[0].forEach((items) => {
                  ydata.push(items.label);
                });

                for (let i = 0; i < datatotal.length; i++) {
                  for (let j = 0; j < datatotal[i].length; j++) {
                    xdata[i].data.push(datatotal[i][j].value);
                  }
                }

                this.departmentRanking(xdata, ydata);
              } else {
                res.data.forEach((items) => {
                  xdata.push(items.label);
                  ydata.push(items.value);
                });
                this.departmentRankingZZ(xdata, ydata);
              }
            } else {
              // this.$message.warning("暂无数据");
              if (this.canvasType == "1") {
                this.departmentRanking();
              } else {
                this.departmentRankingZZ();
              }
            }
          } else {
            this.$message.error(res.message);
          }
        });
    },

    departmentRanking(xdata, ydata) {
      // 基于准备好的dom，初始化echarts实例
      this.teamChart = this.$echarts.init(document.getElementById("bumen"));
      let option = {
        tooltip: {
          trigger: "axis",
        },
        legend: {
          right: 10,
          data: this.titleSvg,
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        toolbox: {
          x: "left",
          feature: {},
        },
        color: ["#6699FF", "#52CCA3", "#ff9933", "#006699", "#4cabce"],
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: ydata,
          axisLine: {
            lineStyle: {
              color: "#999", //x轴的颜色
            },
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: "#999",
            },
          },
        },
        yAxis: {
          type: "value",
          splitLine: {
            // show: false,
            lineStyle: {
              type: "dotted",
            },
          },
          axisTick: {
            show: true, //刻度
          },
          axisLine: {
            //y轴线
            show: false,
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: "#999",
            },
          },
        },
        series: xdata, //展示数据
      };
      this.option = option;
      this.teamChart.setOption(option);

      window.onresize = () => {
        this.teamChart.resize();
        this.myChart1.resize();
      };
    },

    departmentRankingZZ(xdata, ydata) {
      this.myChart1 = this.$echarts.init(document.getElementById("bumenZZ"));
      // 指定图表的配置项和数据
      var option = {
        tooltip: {},
        toolbox: {},
        legend: {
          data: [""],
        },
        xAxis: {
          data: xdata,
          axisLabel: {
            show: true,
            textStyle: {
              color: (value, index) => {
                return index == this.myChart1Index ? "#333" : "#999";
              },
            },
          },
          axisLine: {
            lineStyle: {
              color: "#EBEEF5", //左边线的颜色
            },
          },
        },
        yAxis: [
          {
            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed",
              },
            },
            axisTick: {
              show: false, //刻度
            },
            axisLine: {
              //y轴线
              show: false,
            },
            axisLabel: {
              show: true,
              textStyle: {
                color: "#999",
              },
            },
          },
        ],
        grid: {
          left: 80,
        },
        series: [
          {
            type: "bar",
            barWidth: 10,
            data: ydata,
            showBackground: true,
            backgroundStyle: {
              color: "rgba(235, 238, 245, 1)",
            },
            // 设置折线图颜色
            itemStyle: {
              normal: {
                color: (data) => {
                  let itemColor = "#52CCA3";
                  if (this.myChart1Index !== "") {
                    // 根据点击事件产生的index来判断，设置背景色
                    if (this.myChart1Index == data.dataIndex) {
                      itemColor = "#02c9cc";
                    }
                  }
                  return itemColor;
                },
                width: 6 + "px",
                barBorderRadius: [10, 10, 5, 5],
              },
            },
          },
        ],
      };
      // 使用刚指定的配置项和数据显示图表。
      this.myChart1.setOption(option);
      this.myChart1.on("click", (param) => {
        const pointInPixel = [param.event.offsetX, param.event.offsetY];
        if (this.myChart1.containPixel("grid", pointInPixel)) {
          let xIndex = this.myChart1.convertFromPixel(
            {
              seriesIndex: 0,
            },
            [param.event.offsetX, param.event.offsetY]
          )[0];
          this.myChart1Index = param.dataIndex;
        }
        this.myChart1.setOption(option); //柱形图重构

        window.onresize = () => {
          this.teamChart.resize();
          this.myChart1.resize();
        };
      });
    },

    // 新增客户数列表
    newCustomer() {
      this.axios
        .post("/member/v1/member/count", {
          applicationId: this.listSearch,
          pageNo: this.currentPage1,
          pageSize: this.pageSize,
        })
        .then((res) => {
          // console.log(res);
          if (res.code == 0) {
            this.customerApplist = res.data;
          } else {
            this.$message.error(res.message);
          }
        });
    },
    // 列表刷新
    addlistRefresh() {
      this.currentPage1 = 1;
      this.pageSize = 10;
      this.newCustomer();
    },
    // handleSetLineChartData(type) {
    //   this.lineChartData = lineChartData[type];
    // },
    handleCurrentChange(val) {
      this.currentPage1 = val;
      this.newCustomer();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.newCustomer();
    },
  },
};
</script>
<style lang="scss" scoped>
.picker_select {
  margin-right: 10px;
  /deep/.el-select > .el-input {
    width: 180px;
  }
}
.dashboard-editor-container {
  padding: 10px;
  background-color: rgb(240, 242, 245);
  position: relative;
}
.list {
  background: #fff;
  min-height: 400px;
  position: relative;
  .addcur {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
  }
  .listright {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
.page {
  // margin: 10px 0;
  text-align: right;
  width: 100%;
  background: #fff;
  padding-right: 20px;
  position: absolute;
  bottom: 0px;
  right: 0px;
  z-index: 1000;

  span {
    font-size: 14px;
    color: #666;
    display: inline-block;
    margin-left: 10px;
  }

  .el-pagination {
    display: inline-block;
    vertical-align: middle;
  }
}
.header {
  height: 30px;
  // line-height: 30px;
  padding: 10px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  // min-width: 1000px;
  background-color: #fff;

  .el-button {
    margin-left: 10px;
  }

  > p:first-child {
    font-size: 16px;
    font-weight: bold;
    border-left: 3px solid #2d7ddf;
    padding-left: 10px;
    height: 14px;
    line-height: 14px;
  }

  .timer {
    font-weight: normal;
    display: inline-block;
    margin-left: 15px;
    color: #999999;
    font-size: 14px;
  }

  .el-input__inner {
    width: 260px;
    height: 30px;
    line-height: 30px !important;
  }

  .picker {
    display: inline-block;
    vertical-align: middle;
    margin-right: 10px;
  }
  .top_right {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
  /deep/.el-input__icon {
    margin-top: -10px;
  }

  /deep/ .el-date-editor .el-range-separator {
    line-height: 23px !important;
  }
}
.groupTitle {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px 0;
  p:first-child {
    font-size: 14px;
    font-weight: 600;
    color: #333333;
    padding-left: 10px;
    height: 15px;
    line-height: 15px;
    border-left: 3px solid #2d7ddf;
  }

  span {
    font-weight: normal;
    font-size: 12px;
    color: #666;
  }
  p:hover {
    cursor: pointer;
    span {
      color: #2d7edf;
    }
  }
}

/deep/.el-radio-group {
  margin-right: 20px;
}

.picker_select {
  margin-right: 10px;
  /deep/.el-input--small .el-input__inner {
    height: 30px;
    height: 30px;
  }
  /deep/.el-input__icon {
    margin: 0 !important;
  }
}
</style>
